<!--合约减仓-->
<template>
  <div class="all">
    <div class="bg" v-if="isShow">
      <div class="height60"></div>
      <div class="cell-run">
        <div class="cell-run-left">
          <text class="font24 text3">{{T("账户权益") + "(" + tradePairs.investCoin + ")"}}</text>
          <div class="height12"></div>
          <text class="font24 text2">{{marginBalance}}</text>
        </div>

        <div class="cell-run-left">
          <div class="row acenter">
            <text class="font24 text3">{{T("强平价") + "(" + tradePairs.investCoin + ")"}}</text>
            <LImage class="img-question" @click="questionClick('强平价')" :src="Config.img('wenhao.png')"></LImage>
          </div>

          <div class="height12"></div>
          <text class="font24 text2">{{liquidationPrice}}</text>
        </div>

        <div class="cell-run-right">
          <div class="row acenter">
            <text class="font24 text3">{{T("担保资产率") + "  "}}</text>
            <LImage class="img-question" @click="questionClick('担保资产率')" :src="Config.img('wenhao.png')"></LImage>
          </div>
          <div class="height12"></div>
          <text class="font24 text2">{{riskRate == '--' ? riskRate : riskRate+'%'}}</text>
        </div>
      </div>

      <div class="height60"></div>
      <div class="line bg3"></div>
      <div class="height60"></div>
      <div class="row acenter">
        <text class="font28 text2">{{ T("减仓数量") + "  " }}</text>
        <text class="font24 text3 ptop3 all">{{'('+T("担保资产过低将有强平风险")+')'}}</text>
      </div>

      <div class="height12"></div>
      <div class="title" v-if="title">
        <div class="row acenter">
          <text class="font28 text2">{{ title }}</text>
          <div class="width8" v-if="comment && comment.length"></div>
          <LImage class="explain" v-if="comment && comment.length" :src="Config.img('wenhao.png')" @click="explainClick"></LImage>
        </div>

        <div class="width8"></div>
        <text class="font24 text3" v-if="limits">{{ limits }}</text>
      </div>
      <div :class="['input', 'bg3', this.select ? 'main-b1' : '']">
        <div class="row acenter input-add">
        <div class="add-line2 no1"></div>
        </div>
        
        <input class="input-content font28 text1" v-model="investCoinnNum" type="number" :placeholder="tips" @input="onInput" @focus="onFocus" @blur="onBlur"/>
        <div class="input-line no1"></div>
        <text class="font28 text2" >{{ tradePairs.investCoin }}</text>
      </div>

      <WeexSlideBar1 class="slide" ref="WeexSlideBar" @slideChange="slideChange"></WeexSlideBar1>

      <text class="font24 text3">{{T("减仓资金将自动划转至币币或资金账户。")}}</text>

      <div class="all"></div>
      <div class="bg-start-btn acenter main1" @click="subClick()">
        <text class="font32 text1">{{T('减仓')}}</text>
      </div>
    </div>
    <div class="tips-bg" v-if="math.getNumber(riskRate) !=0 && math.getNumber(riskRate) < 150">
      <text class="font24 tips-text" >{{ T("减仓后策略担保资产率将降到&{1}，请注意强平风险。").replace("&{1}", (riskRate+'%'))}}</text>
    </div>
  </div>
</template>

<script>

//基础配置
import navigator from "@/_js/navigator";
import modal from "@/_js/modal";
import math from "@/_js/math";
import Config from "@/_js/config";
import API from '@/_js/api';
import amContract from "@/upContract/amContract";


const weexFunction = weex.requireModule("WeexFunction");
import weexHttp from "@/_js/https"; ;
const globalEvent = weex.requireModule("globalEvent");

import I18N from "@/_i18n/i18n";
var T = I18N.t;
weexFunction.setTitle(T("减仓"));

export default {

  data() {
    return {
      T: T,
      math:math,
      isShow:false,
      Config: Config,
      
      investCoin: "BTC",
      executeId: undefined,
      configMap: undefined,
      account: undefined,
      tradePairs: undefined,
      apiBean:undefined,
      moneyNum: 0,
      investCoinnNum: '',
      apiData:undefined,

      positionMap:undefined, //持仓信息
      contractMap:undefined, //合约信息

      marginBalance:'', //账户权益
      liquidationPrice:'--', //强平价
      riskRate:'0', //担保资产率
    
      minInvest:'100', //最小投入
      maxInvest:'5000', //最大投入
    };
  },

  mounted() {
    
    this.executeId = navigator.getParam('executeId');
    this.configMap = navigator.getParam('configMap');
    this.account = navigator.getParam('account');
    this.tradePairs = navigator.getParam('tradePairs');
    this.positionMap = navigator.getParam('positionMap');
    this.contractMap = navigator.getParam('contractMap');
    
    var self = this;
    API.getApi(this.tradePairs.apiId, 'YES', (api)=>{

      this.apiBean = api;
      this.upApiMoney();
      this.upData();
      this.isShow = true;
      setTimeout(() => { //滑条未绘制，延时刷新
          this.upSlideBar();
      }, 200);


      //Api更新通知
      globalEvent.addEventListener("apiUp",(e)=>{
        if (self.apiBean.apiId == '') {
          return;
        }
        API.getApi(self.apiBean.apiId, 'YES', (api)=>{
          self.apiBean = api;
          self.upApiMoney();
          self.upSlideBar();
        });
      });
      API.synchroCoinContract(this.apiBean.apiId, 
                              this.tradePairs.contractId, 
                              'contract_usdt');
    });
  },

  methods: {

    /********************************** HTTP*/
    //http减仓库
    httpSub() {

      modal.showLoad();
      var num = math.jian(this.tradePairs.investCoinnNum, this.investCoinnNum,4, 2);
      var configMap = JSON.parse(JSON.stringify(this.configMap));
      configMap.tradePairs[0].investCoinnNum = num;
      configMap.tradePairs[0].baseCoinAmount = num;

      var param = {'apiData':this.apiData,
                  'executeId':this.executeId,
                  'executeConfig':configMap};
      weexHttp.postX("contract/adjustPosition",param,true,(data) => {
          if (data.status == 200) {
            
            var ok = ()=> {
              setTimeout(() => {
                modal.hideLoad();
                modal.toast(T('减仓成功'));
                navigator.back();
              }, 3000);
            };
            API.synchroApi(this.tradePairs.apiId, ok, ok);
          } else {
            modal.hideLoad();
            modal.toast(data.msg);
          }
        }
      );
    },

    /********************************** GET*/
    //获取+字符串
    getAddStr(value) {
      value = math.xiaoShuDelete0(value);
      value = math.addJia(value);
      return value;
    },
    
    /********************************** 更新的方法*/
    //更新可用数量
    upApiMoney() {

      var moneyNum = '0';

      var exchangeName = this.apiBean.exchangeName.toLowerCase();
      
      var coin = API.isExchangeUSDT(exchangeName) ? this.tradePairs.investCoin : this.tradePairs.counterCoin;

      var coins = this.apiBean.linerSwapAssets;
      for (let index = 0; index < coins.length; index++) {
        var assets = coins[index];
        if (assets.currency == coin) {
          moneyNum = math.xiaoshu(assets.withdrawAvailable, 4, 2);
          break;
        }
      }
      this.moneyNum = moneyNum;
    },

    //更新滑条
    upSlideBar() {
      var starStr = "0";
      var endStr =
        math.getNumber(this.maxInvest) > math.getNumber(this.moneyNum)
          ? this.moneyNum
          : this.maxInvest;
      endStr = endStr + "";

      var ratio = this.investCoinnNum.length
        ? math.chu(this.investCoinnNum, endStr, 2, 2)
        : "0";
      ratio = math.getNumber(ratio) > 1 ? "1" : ratio;
      ratio = math.getNumber(endStr) == 0 ? 0 : ratio;

      var a = { starStr: starStr, endStr: endStr, ratio: ratio };

      this.$refs.WeexSlideBar.upSlide(a);
    },

    //更新数据
    upData() {

      //新强平价=强平价+减仓数量/[(多单持仓张数-空单持仓张数)*合约面值]
      var liquidationPrice = ()=> {
        
        if (math.getNumber(this.account.liquidationPrice) == 0) {
          return '--';
        }
        
        if (math.getNumber(this.investCoinnNum) == 0) {
          return this.account.riskRate;
        }
      
        var buyVolume = this.positionMap.buyPosition.volume; //多仓持仓张数
        var sellVolume = this.positionMap.sellPosition.volume; //空仓持仓张数
        var pieceVal = this.contractMap.pieceVal; //合约面值

        var volume  = math.jian(buyVolume, sellVolume);
        var value = math.cheng(volume, pieceVal);
        if (math.getNumber(value) == 0) {
          return '--';
        } 

        value = math.chu(this.investCoinnNum, value);
        value = math.jia(this.account.liquidationPrice, value, xiaoshu, 2);
        if (math.getNumber(value) <= 0) {
          return '--';
        }

        return value;
      }

      //新担保资产率=担保资产率-减仓数量/(多仓持仓担保资产 +空仓持仓担保资产 + 冻结担保资产)。
      var riskRate = ()=>{

        if (math.getNumber(this.account.riskRate) == 0) {
          return '--';
        }

        if (math.getNumber(this.investCoinnNum) == 0) {
          return this.account.riskRate;
        }

        var margin = '0';
        margin  = math.jia(margin, this.positionMap.buyPosition.positionMargin); //多仓持仓担保资产
        margin  = math.jia(margin, this.positionMap.sellPosition.positionMargin); //空仓持仓担保资产
        margin  = math.jia(margin, this.account.marginFrozen); //冻结担保资产
        if (math.getNumber(margin) == 0) {
        return '--';
        }

        var value = math.chu(this.investCoinnNum, margin);
        value = math.cheng(value, '100');
        value = math.jian(this.account.riskRate, value, 2, 2);
        if (math.getNumber(value) <= 0) {
        return '--';
        }

        return value;
      };

      //账户权益
      var xiaoshu = math.getCoin(this.tradePairs.investCoin);
      var marginBalance = math.jian(this.account.marginBalance, this.investCoinnNum, xiaoshu, 2);
      this.marginBalance = Number(marginBalance) < 0 ? '0' : marginBalance;
      
      //新强平价
      this.liquidationPrice = liquidationPrice();

      //新担保资产率
      this.riskRate = riskRate();
    },

    /********************************** 回调*/
    //总投入资金-输入改变
    onInput(e) {

      this.upSlideBar();
      this.upData();
    },

    //滑动条-滑动改变
    slideChange(e) {

      var ratio = e.ratio;
      var endStr = math.getNumber(this.maxInvest) > math.getNumber(this.moneyNum) ? this.moneyNum : this.maxInvest;
      if (math.getNumber(endStr) == 0) {
        this.investCoinnNum = '0';
        return;
      }

      //保留位数
      var xiaoshu = this.getXiaoshu();
      this.investCoinnNum = math.cheng(endStr, ratio, xiaoshu, 2);

      this.upData();
    },

    //获取保留小数位
    getXiaoshu() {
      var xiaoshu = this.tradePairs.baseCoinDecimal;
      xiaoshu = math.getNumber(xiaoshu);
      return xiaoshu;
    },
    
    /********************************** 点击事件 */
    //弹出提示
    questionClick(click) {

      if(click =="强平价"){
        modal.alert(T("预估担保资产率下降到0%时的价格，实际发生强平的价格以交易所为准。"));
        return;
      }

      if(click =="担保资产率"){
        modal.alert(T("担保资产率越低风险越高，当担保资产率下降至0%是将触发交易所强平。"));
        return;
      }

      if(click =="开仓阈值"){
        modal.alert(T("当担保资产率下降到此值之下时，策略将暂停开仓动作，可根据风险承受能力自主调节。"));
        return;
      }
    },

    //划转资产
    transferClick() {
      var param = {'apiId':this.tradePairs.apiId};
      var nav = {'navColor':'#0c0c0c'};
      if (this.tradePairs.exchangeName.toLowerCase() == 'okexv5') {
        navigator.open('', 'home/ApiTransferV5', param, nav);
      } else {
        navigator.open('', 'home/ApiTransfer', param, nav);
      }
    },

    //减仓
    subClick(){

      if (this.investCoinnNum.length == 0) {
        modal.toast(T("请输入减仓数量"));
        return;
      }

      if (math.getNumber(this.investCoinnNum) == 0) {
        modal.toast(T("减仓数量不可为0"));
        return;
      }

      if (math.getNumber(this.investCoinnNum) > math.getNumber(this.moneyNum)) {
        modal.toast(T("可减仓不足"));
        return true;
      }

      amContract.getApiParam(this.apiBean,false, (apiMap)=>{
        this.apiData = apiMap.api;
        this.httpSub();
      });
    },
  },
};
</script>

 
<style src="@/_css/style.css"></style>
<style scoped>

.bg {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 9;

  padding-left: 40px;
  padding-right: 40px;
}

/* =========================公共样式 */
.ptop3 {
  padding-top: 3px;
}
.height12 {
  height: 12px;
}
.height40 {
  height: 40px;
}

.height60{
  height: 60px;
}


.line {
  width: 680px;
  height: 2px;
}


/* =========================基本样式 */
.cell-run {
  flex-direction: row;
  justify-content: space-between;
}
.cell-run-left {
  flex-direction: column;
}
.cell-run-right {
  flex-direction: column;
  align-items: flex-end;
}

.slide {
  width: 670px;
  height: 160px;
  margin-top: 10px;
}

.img-question {
  width: 24px;
  height: 24px;
}

.img-transfer {
  width: 28px;
  height: 28px;
  background-color: brown;
}

.title {
  flex-direction: row;
  align-items: flex-end;
  margin-bottom: 20px;
}

.explain {
  width: 28px;
  height: 28px;
  margin-left: 8px;
  margin-right: 8px;
}

/* =========================输入样式 */
.input {
  flex-direction: row;
  align-items: center;

  height: 88px;
  border-radius: 16px;

  border-width: 2px;
  border-color: transparent;

  padding-left: 40px;
  padding-right: 40px;
}

.input-content {
  flex: 1;
  height: 88px;
  
}

.input-line {
  width: 2px;
  height: 24px;
  margin-left: 20px;
  margin-right: 20px;
}

.input-add{
  width: 24px;
  height: 24px;
  margin-right: 40px;
}

.add-line1 {
  width: 2px;
  height: 24px;
  margin-left: 11px;
  position: absolute;
  
}
.add-line2 {
  width: 24px;
  height: 2px;
  position: absolute;
}

.width8 {
  width: 8px;
}

/* =========================减仓按钮样式 */
.bg-start-btn {
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 80px;
  border-radius: 4px;

  margin-bottom: 70px;
}
.tips-bg {
  position: absolute;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  background-color: rgba(248, 84, 84, 0.1);
  padding-top: 2px;
  height: 60px;
  width: 750px;
}
.tips-text {
  width: 670px;
  color: #F85454;
}
</style>